import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/home'
import Article from '@/views/article'
import Publish from '@/views/publish'
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      },
    ]
  },
]

const router = new VueRouter({
  routes
})

// 如果有token，去的页面是login，不允许并跳转home页，不是login则正常跳转
// 没有token，去login可以，去其他页面则跳转login
// 使用路由前置守卫

router.beforeEach((to, from, next) => {
    Nprogress.start()
  if(getItem()){
    if(to.path.toLowerCase() === '/login'){
      next('/home')
    }else{
      next()
    }
  }else{
    if(to.path.toLowerCase() === '/login'){
      next()
    }else{
      next('/login')
    }
  }
  // 当跳转到自身页面时不会再进入导航后置守卫，会使得进度条一直出于加载状态，需要加上进度条完成的代码
  Nprogress.done()
})

// 导航后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
  console.log('后置守卫：', to, from);
})

const originalPush = VueRouter.prototype.push


VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
